package com.besmart.workflow.core.service.factory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.besmart.workflow.core.exception.ConditionExtractException;
import com.besmart.workflow.core.exception.OperationNodeExtractException;
import com.besmart.workflow.core.exception.WorkflowNodeExtractException;
import com.besmart.workflow.core.model.Constants;
import com.besmart.workflow.core.model.WorkflowNode;
import com.besmart.workflow.core.service.factory.extractor.WorkflowNodeExtractor;
@Service("workflowFactory")
public class WorkflowNodeFactory {
	
	private static final String ROOT_IDENTIFIER = "//";
	@Autowired
	private WorkflowNodeExtractor workflowNodeExtractor;

	public List<WorkflowNode> createWorkflows(Document doc) throws WorkflowNodeExtractException, OperationNodeExtractException, ConditionExtractException {
		List<WorkflowNode> workflowNodes = new ArrayList<WorkflowNode>();
		List<?> workflowElements = doc.selectNodes(ROOT_IDENTIFIER+Constants.WORKFLOW_NODE_NAME);
		Iterator<?> iter = workflowElements.iterator();
		while(iter.hasNext())
		{
			Element workflowElement = (Element)iter.next();
			WorkflowNode node = workflowNodeExtractor.extract(workflowElement);
			workflowNodes.add(node);
		}
		return workflowNodes;
	}
	
}
